<script setup lang="ts">
import { computed, ref, onMounted, reactive } from "vue";
import Big from "big.js";
import { type PlusColumn, PlusSearch } from "plus-pro-components";
import EChartsComponent from "@/components/EChartsComponent/index.vue";
import { getDataBySQLDesc } from "@/api/common";
import { useDictionary } from "@/hooks/useDictionary";
import { message } from "@/utils/message";

defineOptions({
  name: "UnconformanceReason"
});

// 使用局部混入
// gs为供应商
const { dicData, fetchDictionary } = useDictionary({
  action: "public/get_supplier",
  gys: null
});
const searchForm = ref();
const supplierOptions = computed(() => {
  return dicData.value.map(item => ({
    label: item["供应商名称"], // 根据实际接口返回调整字段
    value: item["供应商编号"]
  }));
});
// 将 searchColumns 定义为 computed，当 supplierOptions 更新时，columns 也会跟着更新
const searchColumns = computed<PlusColumn[]>(() => [
  {
    label: "开始时间",
    prop: "kssj",
    fieldProps: {
      valueFormat: "YYYY-MM-DD",
      placeholder: "请选择时间"
      // disabledDate(date: Date) {
      //   if (form.value.jssj) {
      //     return date.getTime() > new Date(form.value.jssj).getTime();
      //   }
      //   return false;
      // }
    },
    valueType: "date-picker"
  },
  {
    label: "结束时间",
    prop: "jssj",
    fieldProps: {
      valueFormat: "YYYY-MM-DD",
      placeholder: "请选择时间"
      // disabledDate(date: Date) {
      //   if (form.value.kssj) {
      //     console.log(date.getTime(), new Date(form.value.kssj).getTime())
      //     return date.getTime() < new Date(form.value.kssj).getTime();
      //   }
      //   return false;
      // }
    },
    valueType: "date-picker"
  },
  {
    label: "供应商",
    prop: "gys",
    valueType: "select",
    fieldProps: {
      filterable: true,
      remote: true,
      placeholder: "请选择供应商",
      remoteMethod: searchCity
    },
    options: supplierOptions.value // 初始为空，后续更新后 searchColumns 也会更新
  }
]);
const searchCity = cityName => {
  fetchDictionary({
    action: "public/get_supplier",
    gys: cityName
  });
};
const form = ref({
  action: "biz/reports/get_iqc_bhgfx_jcxm",
  jydjb: null,
  jydzt: null,
  gys: "", // Y0000076 供应商
  kssj: null, // 2014-07-15 开始时间
  jssj: null //2014-07-15 结束时间
});
const refuseData = ref([]);
const refuseOption = ref({
  tooltip: {
    trigger: "axis",
    position: function (point) {
      return [point[0] - 50, point[1] - 50];
    },
    axisPointer: { type: "cross", crossStyle: { color: "#999" } }
  },
  xAxis: [
    {
      type: "category",
      data: [],
      axisPointer: { type: "shadow" }
    }
  ],
  yAxis: [
    {
      type: "value",
      axisLabel: {
        formatter: "{value}%"
      }
    }
  ],
  series: [
    {
      name: "",
      type: "bar",
      label: { show: true },
      data: []
    }
  ]
});
const tableData = ref([]);
const columns = ref([
  {
    label: "检测项目",
    prop: "检测项目"
  },
  {
    label: "总批次",
    prop: "总批次"
  },
  {
    label: "不良批次",
    prop: "不良批次"
  },
  {
    label: "不良批次率",
    prop: "不良批次率",
    formatter: row => {
      return row["不良批次率"] + "%";
    }
  },
  {
    label: "不良项目占比",
    prop: "不良项目占比",
    formatter: row => {
      return row["不良项目占比"] + "%";
    }
  }
]);
const validateTime = () => {
  const { kssj, jssj } = form.value;
  // 如果两个时间都为空，则验证通过
  if (!kssj && !jssj) {
    return true;
  } else {
    // 两个时间都有的情况下进行比较
    const startTime = new Date(kssj).getTime();
    const endTime = new Date(jssj).getTime();
    if (endTime < startTime) {
      message("结束时间必须大于开始时间", { type: "error" });
      return false;
    } else {
      return true;
    }
  }
};

const handleSearch = async () => {
  let params = {
    ...form.value,
    kssj: form.value.kssj ? form.value.kssj + " 00:00:00" : "",
    jssj: form.value.jssj ? form.value.jssj + " 23:59:59" : ""
  };
  // if (!validateTime()) {
  //   return;
  // }
  const { data } = await getDataBySQLDesc(params);
  if (data) {
    refuseData.value = [];
    data.forEach(item => {
      item["不良批次率"] = Big(Number(item["不良批次率"]))
        .times(100)
        .toFixed(2);
      item["不良项目占比"] = Big(Number(item["不良项目占比"]))
        .times(100)
        .toFixed(2);
      refuseData.value.push({
        name: item["检测项目"],
        value: item["不良项目占比"]
      });
    });
    refuseOption.value.xAxis[0].data = refuseData.value.map(el => {
      return el.name;
    });
    refuseOption.value.series[0].data = refuseData.value.map(el => {
      return Number(el.value);
    });
    tableData.value = data;
  }
};
const getAllParams = async () => {
  let reqParams = {
    action: "public/get_bi_sjfw",
    hsmc: "get_iqc_bhgfx_jcxm"
  };
  const { data } = await getDataBySQLDesc(reqParams);
  data.forEach(element => {
    form.value[element["参数编码"]] = element["参数值"];
  });
  handleSearch();
};
const handleRest = () => {
  form.value = {
    action: "biz/reports/get_iqc_bhgfx_jcxm",
    jydjb: null,
    jydzt: null,
    gys: "", // Y0000076
    kssj: null, // 2014-07-15
    jssj: null //2014-07-15
  };
  getAllParams();
};

onMounted(() => {
  getAllParams();
  // handleSearch();
});
</script>

<template>
  <div class="page-content">
    <el-card>
      <PlusSearch v-model="form" searchText="搜索" resetText="重置" expand-text="展开" retractText="收起"
        :columns="searchColumns" :show-number="2" label-width="80" label-position="right" @search="handleSearch"
        @reset="handleRest" />
    </el-card>
    <el-card class="chart-card mt-[20px]">
      <div class="flex flex-wrap">
        <div class="title w-full text-center py-[20px]">检验项目不良率</div>
        <div class="chart pie-chart w-full sm:w-1/2 lg:w-1/2">
          <div class="charts-title text-center mb-[10px]">不良项目占比</div>
          <EChartsComponent :data="refuseData" type="pie" />
        </div>
        <div class="chart bar-chart w-full sm:w-1/2 lg:w-1/2">
          <EChartsComponent :extraOptions="refuseOption" type="bar" />
        </div>
      </div>
    </el-card>
    <el-card class="mt-[20px]">
      <div class="operate mb-[20px]">
        <el-button type="primary">导出</el-button>
      </div>
      <PureTable ref="tableRef" border row-key="id" alignWhole="center" showOverflowTooltip :data="tableData"
        :columns="columns" :pagination="null" />
    </el-card>
  </div>
</template>

<style lang="css" scoped>
.chart {
  height: 400px;
}

.title {
  font-size: 18px;
  font-weight: bold;
}
</style>
